<template>
  <div>
    <el-header class="bg-white">
      <el-row style="margin-left: 23px; padding-top: 10px">
        <el-col :span="2">
          <el-button @click="handleSelectAll">全部订单</el-button>
        </el-col>
        <el-col :span="2">
          <el-button
            @click="handleSelectByStatus(0)"
            type="text"
            :style="{ color: current_select === '未支付' ? 'red' : 'black' }"
            >未支付</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button
            @click="handleSelectByStatus(1)"
            type="text"
            :style="{ color: current_select === '已支付' ? 'red' : 'black' }"
            >已支付</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button
            @click="handleSelectByStatus(2)"
            type="text"
            :style="{ color: current_select === '已取消' ? 'red' : 'black' }"
            >已取消</el-button
          >
        </el-col>
      </el-row>
    </el-header>

    <!-- 订单列表 -->
    <el-table :data="orderlist" style="margin: 20px 0" border>
      <el-table-column prop="orderId" label="订单号" width="150" />
      <el-table-column prop="totalPrice" label="总价" width="150" />
      <el-table-column label="状态" width="150">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 0"
            type="danger"
            size="mini"
            @click="confirmPay(scope.row)"
          >
            未支付
          </el-button>
          <el-button
            v-else-if="scope.row.status === 1"
            type="success"
            size="mini"
            >已支付</el-button
          >
          <span v-else-if="scope.row.status === 2">已取消</span>
          <span v-else>未知状态</span>
        </template>
      </el-table-column>
      <el-table-column prop="adrId" label="地址号" width="150" />
      <el-table-column prop="createTime" label="创建时间" width="200" />
      <el-table-column label="商品详情">
        <template #default="scope">
          <div v-for="item in scope.row.orderItems" :key="item.orderItemId">
            <el-button
              v-if="item.productId && productNames[item.productId]"
              :type="'text'"
              size="mini"
              @click="toBookDetail(item)"
            >
              {{ productNames[item.productId] }}，数量: {{ item.amount }}
            </el-button>
            <span v-else>加载中...</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <!-- 分页组件 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNow"
        @current-change="selectall"
        @size-change="handleSizeChange"
        :page-sizes="[1, 10, 15, 20]"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import dayjs from "dayjs";
import { jwtDecode } from "jwt-decode";

export default {
  name: "UserOrder",
  data() {
    return {
      orderlist: [], // 用于存储订单数据
      current_select: "全部订单", // 当前选择的状态
      productNames: {},
      status: "",
      total: 0, // 总数据量
      pageSize: 10, // 每页显示条数
      pageNow: 1, // 当前页码
    };
  },

  methods: {
    formatDate(date) {
      return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
    },

    selectall(page = 1) {
      this.pageNow = page; // 更新当前页码
      this.current_select = "全部订单";
      const token = localStorage.getItem("token");
      const decoded = jwtDecode(token);
      //发送请求
      axios
        .get("/getUserOrder", {
          params: {
            pageNow: this.pageNow,
            pageSize: 10,
            userId: decoded.userId,
          },
        })
        .then((response) => {
          const data = response.data;
          console.log("order", data);
          if (data.code === 200) {
            // 将订单数据格式化
            this.orderlist = data.data.data.orders.map((order) => {
              return {
                orderId: order.orderId,
                adrId: order.adrId,
                totalPrice: order.totalPrice,
                status: order.status,
                createTime: this.formatDate(order.createTime), // 日期格式化
                orderItems: order.orderItemList.orderItems || [],
              };
            });
            this.total = data.data.data.orderCount;
          } else {
            this.$message.error("获取订单失败");
          }
        })
        .catch((error) => {
          console.error(error);
          this.$message.error("请求失败，请稍后重试");
        });
    },

    handleSelectAll() {
      this.pageNow = 1; // Reset to the first page
      this.selectall();
    },

    // 每页显示条数改变时
    handleSizeChange(val) {
      this.pageSize = val; // 更新每页条数
      this.selectall(); // 从第一页开始获取数据
      this.pageNow = 1;
    },

    toBookDetail(orderItems) {
      console.log("orderItems", orderItems);
      //获取书籍 id
      let productId = orderItems.productId;
      //前往商品详情页
      console.log("product", productId);
      this.$router.push({
        path: "/product-detail",
        query: { productId: productId },
      });
    },

    fetchProductName(productId) {
      if (!this.productNames[productId]) {
        axios
          .get(`/findProductById?productId=${productId}`)
          .then((response) => {
            if (response.data.code === 200) {
              this.$set(
                this.productNames,
                productId,
                response.data.data.data.productName
              );
            }
          })
          .catch((error) => {
            console.error("获取产品信息失败:", error);
          });
      }
    },

    handleSelectByStatus(status) {
      this.pageNow = 1;
      this.selectbystatus(status);
    },

    selectbystatus(status) {
      this.current_select = "全部订单";
      const token = localStorage.getItem("token");
      const decoded = jwtDecode(token);
      // 根据状态选择订单
      if (status === 0) {
        this.current_select = "未支付";
      } else if (status === 1) {
        this.current_select = "已支付";
      } else if (status === 2) {
        this.current_select = "已取消";
      }

      //发送请求
      axios
        .get("/getUserOrderbystate", {
          params: {
            pageNow: 1,
            pageSize: 10,
            userId: decoded.userId,
            status: status,
          },
        })
        .then((response) => {
          const data = response.data;
          if (data.code === 200) {
            // 将订单数据格式化
            this.orderlist = data.data.data.orders.map((order) => {
              return {
                orderId: order.orderId,
                totalPrice: order.totalPrice,
                status: order.status,
                createTime: this.formatDate(order.createTime), // 日期格式化
                orderItems: order.orderItemList.orderItems || [],
              };
            });
          } else if (data.code === 301) {
            this.orderlist = null;
            this.$message({
              message: "无该状态的订单信息",
              type: "warning",
            });
          } else {
            this.$message.error("获取订单失败");
          }
        })
        .catch((error) => {
          console.error(error);
          this.$message.error("请求失败，请稍后重试");
        });
    },
    confirmPay(row) {
      this.$confirm(
        `确认要支付订单号为 ${row.orderId} 的订单吗？`,
        "确认付款",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.handlePay(row); // 调用付款方法
        })
        .catch(() => {
          this.$message.info("已取消付款");
        });
    },

    handlePay(row) {
      axios
        .post(`/Orderchangestate?orderId=${row.orderId}`, {
          headers: {
            "Content-Type": "application/json", // 设置请求类型为 JSON
          },
        })
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("付款成功");
            row.status = 1;
          } else {
            this.$message.error(response.data.message);
          }
        })
        .catch((error) => {
          console.error("请求失败", error);
          this.$message.error("提交订单失败");
        });
    },
  },

  watch: {
    orderlist: {
      handler(newOrders) {
        if (newOrders && Array.isArray(newOrders)) {
          newOrders.forEach((order) => {
            order.orderItems.forEach((item) => {
              this.fetchProductName(item.productId);
            });
          });
        }
      },
      immediate: true,
    },
  },

  created() {
    this.selectall();
  },
};
</script>

<style>
.bg-white {
  background: white;
  border: 2px solid #dde1e7;
}
.status {
  font-size: 20px;
  font-weight: bolder;
  color: #b5c5d9;
  margin-top: 6px;
  padding-left: 200px;
}
</style>
